"""
真实WVP集成API端点
Real WVP Integration API Endpoints

直接从Java后端获取真实WVP数据并转换为摄像头
"""
import logging
from datetime import datetime
from typing import List, Dict, Any, Optional
from fastapi import APIRouter, HTTPException, Query

from api.services import CameraService
from real_java_wvp_client import RealJavaWVPClient
from database.simple_db import get_database_manager

logger = logging.getLogger(__name__)
router = APIRouter()


@router.get("/test-java-connection")
async def test_java_wvp_connection():
    """测试Java后端WVP连接"""
    try:
        logger.info("🧪 测试Java后端WVP连接...")
        
        async with RealJavaWVPClient() as client:
            result = await client.sync_real_wvp_data()
            
            if result["success"]:
                return {
                    "success": True,
                    "message": "Java后端WVP连接成功",
                    "wvp_url": result["wvp_url"],
                    "api_endpoint": result["api_endpoint"],
                    "total_devices": result["total_devices"],
                    "total_channels": result["total_channels"],
                    "test_time": datetime.now().isoformat()
                }
            else:
                raise HTTPException(
                    status_code=503,
                    detail=f"Java后端WVP连接失败: {result['error']}"
                )
                
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"测试Java后端WVP连接失败: {e}")
        raise HTTPException(status_code=500, detail=f"测试连接失败: {str(e)}")


@router.post("/sync-from-java")
async def sync_wvp_from_java():
    """从Java后端同步WVP数据到本地数据库"""
    try:
        logger.info("📥 开始从Java后端同步WVP数据...")
        
        db = get_database_manager()
        
        # 1. 获取真实WVP数据
        async with RealJavaWVPClient() as client:
            result = await client.sync_real_wvp_data()
            
            if not result["success"]:
                raise HTTPException(
                    status_code=404,
                    detail=f"无法从Java后端获取WVP数据: {result['error']}"
                )
        
        logger.info(f"从Java后端获取到 {result['total_devices']} 个设备和 {result['total_channels']} 个通道")
        
        # 2. 清空现有WVP数据
        logger.info("🗑️ 清空现有WVP数据...")
        db.execute_update("DELETE FROM wvp_devices", ())
        db.execute_update("DELETE FROM wvp_channels", ())
        
        devices = result["devices"]
        channels_map = result["channels"]
        
        synced_devices = 0
        synced_channels = 0
        
        # 3. 同步设备到数据库
        logger.info("💾 同步设备到数据库...")
        for device in devices:
            device_id = (device.get("deviceId") or 
                       device.get("id") or 
                       device.get("device_id"))
            
            if not device_id:
                continue
            
            device_name = (device.get("name") or 
                         device.get("deviceName") or 
                         device.get("device_name") or 
                         f"设备-{device_id}")
            
            # 插入设备
            device_query = """
                INSERT INTO wvp_devices (
                    device_id, device_name, manufacturer, model, ip, port,
                    status, register_time, keepalive_time, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
            """
            
            device_params = (
                device_id,
                device_name,
                device.get("manufacturer", ""),
                device.get("model", ""),
                device.get("ip") or device.get("hostAddress", ""),
                device.get("port", 5060),
                "online" if device.get("online") else "offline"
            )
            
            db.execute_insert(device_query, device_params)
            synced_devices += 1
            logger.info(f"  ✅ 同步设备: {device_id} ({device_name})")
            
            # 4. 同步通道到数据库
            channels = channels_map.get(device_id, [])
            
            if not channels:
                # 如果没有通道，创建默认通道
                channels = [{
                    "channelId": device_id,
                    "name": f"{device_name}-默认通道",
                    "status": "ON" if device.get("online") else "OFF",
                    "address": f"{device_name}位置",
                    "longitude": 0.0,
                    "latitude": 0.0
                }]
            
            for channel in channels:
                channel_id = (channel.get("channelId") or 
                            channel.get("id") or 
                            channel.get("channel_id") or 
                            device_id)
                
                channel_name = (channel.get("name") or 
                              channel.get("channelName") or 
                              channel.get("channel_name") or 
                              f"通道-{channel_id}")
                
                # 插入通道
                channel_query = """
                    INSERT INTO wvp_channels (
                        device_id, channel_id, channel_name, status, 
                        longitude, latitude, address, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
                """
                
                channel_params = (
                    device_id,
                    channel_id,
                    channel_name,
                    "online" if channel.get("status") == "ON" else "offline",
                    channel.get("longitude", 0.0),
                    channel.get("latitude", 0.0),
                    channel.get("address", f"{device_name}位置")
                )
                
                db.execute_insert(channel_query, channel_params)
                synced_channels += 1
                logger.info(f"    ✅ 同步通道: {channel_id} ({channel_name})")
        
        return {
            "success": True,
            "message": "从Java后端同步WVP数据成功",
            "source": result["wvp_url"],
            "api_endpoint": result["api_endpoint"],
            "synced_devices": synced_devices,
            "synced_channels": synced_channels,
            "total_devices": result["total_devices"],
            "total_channels": result["total_channels"],
            "sync_time": datetime.now().isoformat()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"从Java后端同步WVP数据失败: {e}")
        raise HTTPException(status_code=500, detail=f"同步失败: {str(e)}")


@router.post("/convert-to-cameras-real")
async def convert_wvp_to_cameras_real():
    """将WVP设备转换为摄像头 - 使用真实Java后端数据"""
    try:
        logger.info("🚀 开始从Java后端获取真实WVP数据并转换为摄像头...")
        
        camera_service = CameraService()
        db = get_database_manager()
        
        # 1. 首先从Java后端同步最新数据
        sync_result = await sync_wvp_from_java()
        
        if not sync_result.get("success"):
            raise HTTPException(
                status_code=404,
                detail="无法从Java后端同步WVP数据"
            )
        
        logger.info(f"同步完成: {sync_result['synced_devices']} 个设备, {sync_result['synced_channels']} 个通道")
        
        # 2. 将WVP设备转换为摄像头
        logger.info("🔄 开始将WVP设备转换为摄像头...")
        
        wvp_devices = db.execute_query("SELECT * FROM wvp_devices")
        converted_count = 0
        skipped_count = 0
        error_count = 0
        
        for device in wvp_devices:
            device_id = device['device_id']
            device_name = device.get('device_name', device_id)
            
            logger.info(f"处理设备: {device_id} ({device_name})")
            
            # 获取设备通道
            channels = db.execute_query("SELECT * FROM wvp_channels WHERE device_id = ?", (device_id,))
            
            if not channels:
                logger.warning(f"  设备 {device_id} 没有通道，跳过")
                error_count += 1
                continue
            
            logger.info(f"  设备 {device_id} 有 {len(channels)} 个通道")
            
            # 为每个通道创建摄像头
            for channel in channels:
                channel_id = channel['channel_id']
                channel_name = channel.get('channel_name', f'通道-{channel_id}')
                
                # 检查是否已经有对应的摄像头
                existing_camera = db.get_camera_by_wvp_device(device_id, channel_id)
                if existing_camera:
                    logger.info(f"    通道 {channel_id} 已有对应摄像头 {existing_camera['name']}，跳过")
                    skipped_count += 1
                    continue
                
                # 生成唯一的摄像头名称
                base_name = f"{device_name}-{channel_name}"
                unique_name = base_name
                counter = 1
                
                while db.get_camera_by_name(unique_name):
                    unique_name = f"{base_name}_{counter}"
                    counter += 1
                
                # 创建摄像头数据
                camera_data = {
                    'name': unique_name,
                    'wvp_device_id': device_id,
                    'wvp_channel_id': channel_id,
                    'location': channel.get('address', f"{device_name}位置"),
                    'longitude': float(channel.get('longitude', 0.0)),
                    'latitude': float(channel.get('latitude', 0.0)),
                    'description': f"从Java后端WVP设备 {device_name}({device_id}) 通道 {channel_id} 转换的摄像头",
                    'ai_enabled': True,
                    'status': 'online' if channel.get('status') == 'online' else 'offline',
                    'rtsp_url': f"rtsp://{device.get('ip', '192.168.1.100')}:554/h264/ch{channel_id}/main/av_stream"
                }
                
                try:
                    camera_id = await camera_service.create_camera(camera_data)
                    if camera_id:
                        converted_count += 1
                        logger.info(f"    ✅ 成功转换通道 {channel_id} 为摄像头 {camera_id} ({unique_name})")
                    else:
                        logger.error(f"    ❌ 转换通道 {channel_id} 失败: 未返回摄像头ID")
                        error_count += 1
                except Exception as e:
                    logger.error(f"    ❌ 转换通道 {channel_id} 失败: {e}")
                    error_count += 1
        
        # 3. 验证结果
        total_cameras = db.execute_query("SELECT COUNT(*) as count FROM cameras")[0]['count']
        wvp_cameras = db.execute_query("SELECT COUNT(*) as count FROM cameras WHERE wvp_device_id IS NOT NULL")[0]['count']
        
        logger.info("🎉 WVP设备转换完成!")
        logger.info(f"  总设备数: {len(wvp_devices)}")
        logger.info(f"  新建摄像头: {converted_count}")
        logger.info(f"  跳过摄像头: {skipped_count}")
        logger.info(f"  错误数量: {error_count}")
        logger.info(f"  数据库总摄像头: {total_cameras}")
        logger.info(f"  WVP摄像头: {wvp_cameras}")
        
        return {
            "success": True,
            "message": "WVP设备转换完成（使用Java后端真实数据）",
            "source": sync_result.get("source", "Java后端"),
            "sync_result": {
                "synced_devices": sync_result["synced_devices"],
                "synced_channels": sync_result["synced_channels"]
            },
            "conversion_result": {
                "total_devices": len(wvp_devices),
                "converted_cameras": converted_count,
                "skipped_cameras": skipped_count,
                "error_count": error_count
            },
            "database_stats": {
                "total_cameras": total_cameras,
                "wvp_cameras": wvp_cameras
            },
            "conversion_time": datetime.now().isoformat()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"WVP设备转换失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"WVP设备转换失败: {str(e)}")


@router.get("/devices-real")
async def get_wvp_devices_real():
    """获取真实WVP设备列表（直接从Java后端）"""
    try:
        logger.info("📡 直接从Java后端获取WVP设备列表...")
        
        async with RealJavaWVPClient() as client:
            result = await client.sync_real_wvp_data()
            
            if not result["success"]:
                raise HTTPException(
                    status_code=404,
                    detail=f"无法从Java后端获取WVP设备: {result['error']}"
                )
            
            devices = result["devices"]
            channels_map = result["channels"]
            
            # 转换为统一格式
            formatted_devices = []
            for device in devices:
                device_id = (device.get("deviceId") or 
                           device.get("id") or 
                           device.get("device_id"))
                
                device_name = (device.get("name") or 
                             device.get("deviceName") or 
                             device.get("device_name") or 
                             f"设备-{device_id}")
                
                channels = channels_map.get(device_id, [])
                
                formatted_device = {
                    "device_id": device_id,
                    "device_name": device_name,
                    "manufacturer": device.get("manufacturer", ""),
                    "model": device.get("model", ""),
                    "ip": device.get("ip") or device.get("hostAddress", ""),
                    "port": device.get("port", 5060),
                    "status": "online" if device.get("online") else "offline",
                    "channel_count": len(channels),
                    "register_time": device.get("registerTime", ""),
                    "keepalive_time": device.get("keepaliveTime", ""),
                    "source": "Java后端实时数据"
                }
                
                formatted_devices.append(formatted_device)
            
            return {
                "success": True,
                "devices": formatted_devices,
                "total_devices": len(formatted_devices),
                "total_channels": result["total_channels"],
                "source": result["wvp_url"],
                "api_endpoint": result["api_endpoint"],
                "fetch_time": datetime.now().isoformat()
            }
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取真实WVP设备列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取设备列表失败: {str(e)}")


@router.get("/devices/{device_id}/channels-real")
async def get_device_channels_real(device_id: str):
    """获取真实设备通道列表（直接从Java后端）"""
    try:
        logger.info(f"📡 直接从Java后端获取设备 {device_id} 的通道列表...")
        
        async with RealJavaWVPClient() as client:
            # 先找到活跃的WVP服务
            service_info = await client.find_active_wvp_service()
            if not service_info or not service_info[0]:
                raise HTTPException(
                    status_code=503,
                    detail="无法连接到Java后端WVP服务"
                )
            
            base_url, api_endpoint = service_info
            
            # 尝试登录
            await client.login(base_url)
            
            # 获取设备通道
            channels = await client.get_device_channels_from_java(base_url, device_id)
            
            # 转换为统一格式
            formatted_channels = []
            for channel in channels:
                channel_id = (channel.get("channelId") or 
                            channel.get("id") or 
                            channel.get("channel_id") or 
                            device_id)
                
                channel_name = (channel.get("name") or 
                              channel.get("channelName") or 
                              channel.get("channel_name") or 
                              f"通道-{channel_id}")
                
                formatted_channel = {
                    "device_id": device_id,
                    "channel_id": channel_id,
                    "channel_name": channel_name,
                    "status": "online" if channel.get("status") == "ON" else "offline",
                    "longitude": channel.get("longitude", 0.0),
                    "latitude": channel.get("latitude", 0.0),
                    "address": channel.get("address", ""),
                    "channel_type": channel.get("channelType", 0),
                    "sub_count": channel.get("subCount", 0),
                    "has_audio": channel.get("hasAudio", False),
                    "ptz_type": channel.get("ptzType", 0),
                    "source": "Java后端实时数据"
                }
                
                formatted_channels.append(formatted_channel)
            
            return {
                "success": True,
                "device_id": device_id,
                "channels": formatted_channels,
                "total_channels": len(formatted_channels),
                "source": base_url,
                "fetch_time": datetime.now().isoformat()
            }
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取设备 {device_id} 真实通道列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取通道列表失败: {str(e)}")


@router.get("/status")
async def get_wvp_status():
    """获取WVP服务状态"""
    try:
        # 检查Java后端连接
        java_status = {"connected": False, "url": None, "devices": 0, "channels": 0}
        
        try:
            async with RealJavaWVPClient() as client:
                result = await client.sync_real_wvp_data()
                if result["success"]:
                    java_status = {
                        "connected": True,
                        "url": result["wvp_url"],
                        "api_endpoint": result["api_endpoint"],
                        "devices": result["total_devices"],
                        "channels": result["total_channels"]
                    }
        except Exception as e:
            logger.debug(f"Java后端连接检查失败: {e}")
        
        # 检查本地数据库
        db = get_database_manager()
        
        try:
            local_devices = db.execute_query("SELECT COUNT(*) as count FROM wvp_devices")[0]['count']
            local_channels = db.execute_query("SELECT COUNT(*) as count FROM wvp_channels")[0]['count']
            local_cameras = db.execute_query("SELECT COUNT(*) as count FROM cameras WHERE wvp_device_id IS NOT NULL")[0]['count']
        except:
            local_devices = local_channels = local_cameras = 0
        
        return {
            "java_backend": java_status,
            "local_database": {
                "devices": local_devices,
                "channels": local_channels,
                "wvp_cameras": local_cameras
            },
            "status_time": datetime.now().isoformat()
        }
        
    except Exception as e:
        logger.error(f"获取WVP状态失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取状态失败: {str(e)}")